package city.spring.modules.medicine.controller;

import city.spring.modules.medicine.entity.MedicinedeliveryEntity;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.medicine.service.MedicinedeliveryService;
import city.spring.modules.medicine.service.MedicinestorehouseService;
import city.spring.modules.medicine.vo.MedicinedeliveryVO;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：药品出库表
 *
 * @author 谢金婷
 * @date 2020-07-08 16:16:50
 */
@RestController
@RequestMapping("/medicinedelivery")
public class MedicinedeliveryController extends ApiController {
    private final MedicinedeliveryService medicinedeliveryService;
    private final EmployeeService employeeService;
    private final MedicineService medicineService;
    private final MedicinestorehouseService storehouseService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicinedeliveryEntity, ?>> entityOrderFields;

    public MedicinedeliveryController(MedicinedeliveryService medicinedeliveryService, EmployeeService employeeService, MedicineService medicineService, MedicinestorehouseService storehouseService) {
        this.medicinedeliveryService = medicinedeliveryService;
        this.employeeService = employeeService;
        this.medicineService = medicineService;
        this.storehouseService = storehouseService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicinedeliveryEntity::getId);
        entityOrderFields.add(MedicinedeliveryEntity::getMedicinereceiptId);
        entityOrderFields.add(MedicinedeliveryEntity::getWstorehouseId);
        entityOrderFields.add(MedicinedeliveryEntity::getDestination);
        entityOrderFields.add(MedicinedeliveryEntity::getDeliverydate);
        entityOrderFields.add(MedicinedeliveryEntity::getUserId);
        entityOrderFields.add(MedicinedeliveryEntity::getUsersId);
        entityOrderFields.add(MedicinedeliveryEntity::getGmtCreate);
        entityOrderFields.add(MedicinedeliveryEntity::getGmtModified);
        entityOrderFields.add(MedicinedeliveryEntity::getDtype);
    }

    /**
     * 获取全部的 <strong>药品出库表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MedicinedeliveryEntity entity) {
        LambdaQueryChainWrapper<MedicinedeliveryEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>药品出库表</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MedicinedeliveryVO entity, Date[] deliverydate) {

        QueryWrapper<? extends MedicinedeliveryEntity> queryWrapper = buildQuery(entity);
        if (deliverydate != null && deliverydate.length == 2) {
            queryWrapper.ge("t1.deliverydate", deliverydate[0]);
            queryWrapper.le("t1.deliverydate", deliverydate[1]);
        }
        return success(medicinedeliveryService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));


//        LambdaQueryChainWrapper<MedicinedeliveryEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicinedeliveryEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MedicinedeliveryEntity record : page.getRecords()) {
//            try {
//                MedicinestorehouseEntity storehouseEntity = storehouseService.getById(record.getWstorehouseId());
//                record.setWsname(storehouseEntity.getSname());
//            } catch (Exception ignore) {
//                record.setWstorehouseId(null);
//                record.setWsname("< 找不到仓库 >");
//            }
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getUserId());
//                record.setName(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setUserId(null);
//                record.setName("< 找不到领用人 >");
//            }
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getUsersId());
//                record.setUsername(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setUsersId(null);
//                record.setUsername("< 找不到登记人 >");
//            }
//            try {
//                MedicineEntity medicineEntity = medicineService.getById(record.getMedicineId());
//                record.setMname(medicineEntity.getName());
//            } catch (Exception ignore) {
//                record.setMedicineId(null);
//                record.setMname("< 找不到药品 >");
//            }
//        }
//        return success(page);
    }

    /**
     * 获取一个 <strong>药品出库表</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
//        return success(medicinedeliveryService.getMedicinedeliveryById(id));

        QueryWrapper<MedicinedeliveryVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicinedeliveryVO> records = medicinedeliveryService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>药品出库表</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MedicinedeliveryEntity entity, @NonNull Principal user) {
        medicinedeliveryService.saveMedicinedelivery(entity, user);
        return success(entity);
    }

    /**
     * 修改一个 <strong>药品出库表</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MedicinedeliveryEntity entity) {
        entity.setId(Integer.valueOf(id));
        medicinedeliveryService.updateMedicinedelivery(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>药品出库表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicinedeliveryService.deleteMedicinedelivery(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品出库表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicinedeliveryService.deleteMedicinedelivery(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicinedeliveryEntity> buildLambdaQuery(MedicinedeliveryEntity entity) {
        LambdaQueryChainWrapper<MedicinedeliveryEntity> lambdaQuery = medicinedeliveryService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, MedicinedeliveryEntity::getId, entity.getId());
        lambdaQuery.eq(entity.getMedicinereceiptId() != null, MedicinedeliveryEntity::getMedicinereceiptId, entity.getMedicinereceiptId());
        lambdaQuery.eq(entity.getWstorehouseId() != null, MedicinedeliveryEntity::getWstorehouseId, entity.getWstorehouseId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDestination()), MedicinedeliveryEntity::getDestination, entity.getDestination());
        lambdaQuery.eq(entity.getDeliverydate() != null, MedicinedeliveryEntity::getDeliverydate, entity.getDeliverydate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUserId()), MedicinedeliveryEntity::getUserId, entity.getUserId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUsersId()), MedicinedeliveryEntity::getUsersId, entity.getUsersId());
        lambdaQuery.eq(entity.getGmtCreate() != null, MedicinedeliveryEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MedicinedeliveryEntity::getGmtModified, entity.getGmtModified());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDtype()), MedicinedeliveryEntity::getDtype, entity.getDtype());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicinedeliveryEntity> buildQuery(MedicinedeliveryVO entity) {
        QueryWrapper<MedicinedeliveryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(entity.getId() != null, "t1.id", entity.getId());
        wrapper.eq(entity.getMedicinereceiptId() != null, "t1.medicinereceipt_id", entity.getMedicinereceiptId());
        wrapper.eq(entity.getWstorehouseId() != null, "t1.wstorehouse_id", entity.getWstorehouseId());
        wrapper.like(StringUtils.isNotBlank(entity.getWsname()), "t2.sname", entity.getWsname());
        wrapper.like(entity.getMedicineId() != null, "t1.medicine_id", entity.getMedicineId());
        wrapper.like(StringUtils.isNotBlank(entity.getMname()), "t3.name", entity.getMname());
        wrapper.like(StringUtils.isNotBlank(entity.getDestination()), "t1.destination", entity.getDestination());
//        wrapper.eq(entity.getDeliverydate() != null, "t1.deliverydate", entity.getDeliverydate());
        wrapper.like(StringUtils.isNotBlank(entity.getUserId()), "t1.user_id", entity.getUserId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t4.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getUsersId()), "t1.users_id", entity.getUsersId());
        wrapper.like(StringUtils.isNotBlank(entity.getUsername()), "t5.name", entity.getUsername());
        return wrapper;
    }

}
